const cheerio = require('cheerio');
const _ = require('underscore');
const Base = require('./_base')
const path = window.require('path');
const md5 = require('js-md5');

export default class Gather extends Base{
  constructor(reportCb) {
    super(reportCb);
    this.enterurl = 'http://www.alfdafre.it/it/prodotti.aspx'
    this.pathname = path.resolve('data/' + md5(this.enterurl))
  }

  getProductUrls = async() => {

    let res = await fetch(this.enterurl).then(res => res.text());
    let $ = cheerio.load(res)
    var html=$('.pure-g').html();
    let urls = []
    if($("div.pure-g").children().length<1 || $("div.pure-g")===undefined)return false;
  	$("div.pure-g").children().each(function(i,e){
  		if($('a',$(this).html()).eq(0).attr('href')===undefined)return false;
  		if($('a',$(this).html()).eq(0).attr('href').indexOf('sottocategorie')>=0){
  			urls.push($('a',$(this).html()).eq(0).attr('href'));
  		}
  	});

    let rurls = []

    for (let i of _.range(urls.length)) {
      let url = urls[i]
      this.status.msg = '获取列表'
      this.status.current = i + 1
      this.status.count = urls.length
      this.reportCb(this.status)

      console.log('fetch list', url)
      let res = await fetch("http://www.alfdafre.it"+url).then(res => res.text());
      let $ = cheerio.load(res)
      let goods_list=$('.pure-g').html();
  		if($("div.pure-g").children().length<1 || $("div.pure-g")===undefined)return false;
  		$("div.pure-g").children().each(function(i,e){
  			if($('a',$(this).html()).eq(0).attr('href')===undefined)return false;
  			if($('a',$(this).html()).eq(0).attr('href').indexOf('prodotto')>0){
  				rurls.push($('a',$(this).html()).eq(0).attr('href'));
  			}
  		});
    }
    return rurls.map(v=>'http://www.alfdafre.it'+v)
  }

  getProduct = async(url) => {

    console.log('fetch product', url)
    let res = await fetch(url).then(res => res.text());
    let $ = cheerio.load(res)

    // 获取商品的详细地址
    var product={};
				let good=$('.art').html();

				product.origin_url = url;
				product.brand_num='alfdafre';
				product.name=$('.art__title',good).eq(0).text();
				product.date=new Date().getTime();
				product.description=$('.art__text',good).text() || '';
				product.images=[];
				product.path=[];
				product.local_path=[];

				if($('.top__i')===undefined || $('.top__i').length<1)return false;

				$('.top__i').each(function(j,el){
					if($('img',$(this).html())===undefined)return false;
					let img=$('img',$(this).html()).attr('data-src');
					if(img===undefined)return false;
          product.images.push({"pic_url": img});
				});

    return product
  }
}
